package com.kbtd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kbtd.dto.Result;
import com.kbtd.dto.ScrollResult;
import com.kbtd.dto.UserDTO;
import com.kbtd.entity.Blog;
import com.kbtd.entity.Follow;
import com.kbtd.entity.User;
import com.kbtd.mapper.BlogMapper;
import com.kbtd.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kbtd.service.IFollowService;
import com.kbtd.service.IUserService;
import com.kbtd.constant.SystemConstants;
import com.kbtd.utils.UserHolder;
import com.kbtd.utils.redis.RedisUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.kbtd.constant.RedisConstants.BLOG_LIKED_KEY_PREFIX;
import static com.kbtd.constant.RedisConstants.FEED_KEY_PREFIX;
import static com.kbtd.constant.SystemConstants.FOLLOW_BLOG_SIZE;
import static com.kbtd.constant.SystemConstants.FOLLOW_BLOG_START_TIME;

/**
 * 博客服务类
 *
 * @author wp
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;

    //保存博客并推送给粉丝
    //推送机制：Feed(写扩散)
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        blog.setUserId(userId);
        // 保存探店博文
        save(blog);
        //如果保存成功，则获取保存笔记的发布者id，用该id去follow_user表中查对应的粉丝id
        List<Follow> followUsers = followService.query().eq("follow_user_id", userId).list();
        for (Follow follow : followUsers) {
            Long followId = follow.getUserId();
            String feedKey = RedisUtils.createKey(FEED_KEY_PREFIX, followId.toString());
            //推送数据,每一个粉丝都有自己的收件箱
            stringRedisTemplate.opsForZSet().add(feedKey, blog.getId().toString(), System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    //博客查询
    @Override
    public Result queryById(Long id) {
        Blog blog = query().eq("id", id).one();
        if (blog == null) {
            return Result.fail("笔记不存在！");
        }
        completeBlogMsg(blog);
        return Result.ok(blog);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            completeBlogMsg(blog);
        });
        return Result.ok(records);
    }

    //补充博客信息
    private void completeBlogMsg(Blog blog) {
        Long authorId = blog.getUserId();
        User author = userService.getById(authorId);
        blog.setName(author.getNickName());
        blog.setIcon(author.getIcon());
        String likedKey = RedisUtils.createKey(BLOG_LIKED_KEY_PREFIX, blog.getId().toString());
        Long userId = UserHolder.getUser().getId();
        Boolean isLike = stringRedisTemplate.opsForSet().isMember(likedKey, userId.toString());
        blog.setIsLike(Boolean.TRUE.equals(isLike));
    }

    //博客点赞/取消点赞
    @Override
    public Result likeBlog(Long blogId) {
        String likedKey = RedisUtils.createKey(BLOG_LIKED_KEY_PREFIX, blogId.toString());

        Long userId = UserHolder.getUser().getId();
        Double score = stringRedisTemplate.opsForZSet().score(likedKey, userId.toString());
        if (!ObjectUtils.isEmpty(score)) {
            boolean succeed = update()
                    .setSql("liked = liked - 1").eq("id", blogId).update();
            if (succeed) {
                stringRedisTemplate.opsForZSet().remove(likedKey, userId.toString());
            }
        } else {
            boolean succeed = update()
                    .setSql("liked = liked + 1").eq("id", blogId).update();
            if (succeed) {
                stringRedisTemplate.opsForZSet().add(likedKey, userId.toString(), System.currentTimeMillis());
            }
        }
        return Result.ok();
    }

    //查询博客点赞用户
    @Override
    public Result queryBlogLikeUser(Long blogId) {
        String likedKey = RedisUtils.createKey(BLOG_LIKED_KEY_PREFIX, blogId.toString());
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(likedKey, 0, 5);
        //如果是空的(可能没人点赞)，直接返回一个空集合
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        //将ids使用`,`拼接，SQL语句查询出来的结果并不是按照我们期望的方式进行排
        //所以我们需要用order by field来指定排序方式，期望的排序方式就是按照查询出来的id进行排序
        String idsStr = StrUtil.join(",", ids);
        //select * from tb_user where id in (ids[0], ids[1] ...) order by field(id, ids[0], ids[1] ...)
        List<UserDTO> userDTOS = userService.query().in("id", ids)
                .last("order by field(id," + idsStr + ")")
                .list().stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    //查询关注博主的博客
    @Override
    public Result queryBlogOfFollow(Long lastTime, Integer offset) {
        //1. 获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2. 查询该用户收件箱（之前我们存的key是固定前缀 + 粉丝id），所以根据当前用户id就可以查询是否有关注的人发了笔记
        String key = RedisUtils.createKey(FEED_KEY_PREFIX, userId.toString());
        Set<ZSetOperations.TypedTuple<String>> typeTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, FOLLOW_BLOG_START_TIME, lastTime, offset, FOLLOW_BLOG_SIZE);
        //3. 非空判断
        if (typeTuples == null || typeTuples.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //4. 解析数据，blogId、lastTime（时间戳）、offset，这里指定创建的list大小，可以略微提高效率，因为我们知道这个list就得是这么大
        ArrayList<Long> ids = new ArrayList<>(typeTuples.size());
        for (ZSetOperations.TypedTuple<String> typeTuple : typeTuples) {
            //4.1 添加id
            ids.add(Long.valueOf(typeTuple.getValue()));
            //4.2 获取score（时间戳）
            long time = typeTuple.getScore().longValue();
            //计算偏移量
            if (time == lastTime){
                offset++;
            }else {
                lastTime = time;
                offset = 1;
            }
        }
        //解决SQL的in不能排序问题，手动指定排序为传入的ids
        String idsStr = StrUtil.join(",");

        //5. 根据id查询blog
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idsStr + ")").list();
        blogs.forEach(this::completeBlogMsg);
        //6. 封装结果并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(offset);
        scrollResult.setLastTime(lastTime);
        return Result.ok(scrollResult);
    }
}
